﻿import axios from 'axios';
import qs from 'qs';
import { vm } from '../main';
axios.interceptors.request.use(config => {
    vm.$Loading.start();
    return config;
}, error => {
    return Promise.reject(error);
});
axios.interceptors.response.use(response => {
    vm.$Loading.finish();
    return response;
}, error => {
    return Promise.resolve(error.response);
});
function errorState (response) {
    // vm.$Loading.error();
    // 如果http状态码正常，则直接返回数据
    if (response && (response.status === 200 || response.status === 304 || response.status === 400)) {
        return response;// 如果不需要除了data之外的数据，可以直接 return response.data
    } else {
        alert('网络异常,请稍后再试！');
    }
}
function successState (res, resolve) {
    vm.$Loading.finish();
    if (res.data.status === 'ERROR' && !res.data.obj) { // 统一判断后端返回的错误码
        alert(res.data.status);
    } else {
        resolve(res.data.obj);
    }
}
// 本地API: http://192.168.9.149:8080
// SERVER API: http://10.72.30.17:8080/
export const http = (opts, data, vm) => {
    let httpDefaultOpts = { // http默认配置
        method: opts.method || 'post',
        baseURL: 'http://192.2.2.138/api/',
        url: opts.url,
        timeout: opts.timeout || 20000,
        params: data,
        data: qs.stringify(data),
        headers: opts.headers
    };
    if (httpDefaultOpts.method && httpDefaultOpts.method.toLowerCase() === 'get') {
        delete httpDefaultOpts.data;
    } else {
        delete httpDefaultOpts.params;
    }
    // 以下为需要上传文件时ajax的调整。
    // 参数中需要上传文件的部分
    if (opts['Content-Type'] === 'multipart/form-data') {
        httpDefaultOpts.headers = Object.assign(httpDefaultOpts.headers, {
            'Content-Type': 'multipart/form-data',
            'Access-Control-Allow-Origin': '*'
        });
        let formData = new FormData();
        for (let Key in data) {
            formData.append(Key, data[Key]);
        }
        opts.files.forEach(element => {
            formData.append(element.key, element.file, element.name);
        });
        // httpDefaultOpts.method = 'post';
        httpDefaultOpts.data = formData;
    }
    let promise = new Promise(function (resolve, reject) {
        console.log(httpDefaultOpts)
        axios(httpDefaultOpts).then(
            (res) => {
                successState(res, resolve);
            }
        ).catch(
            (response) => {
                errorState(response);
                reject(response.data);
            }
        );
    });
    return promise;
};
